package com.pos.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.storage.StorageManager;
import android.util.Log;

public class SDFile {
	
	public static int FILE_TYPE_APP = 0x00;
	public static int FILE_TYPE_FIRMWARE = 0x01;
	public static int FILE_TYPE_32550_OS = 0x02;
	
    public static String getSecondaryStoragePath(Context context) {  
        try {  
            StorageManager sm = (StorageManager) (context.getSystemService(Context.STORAGE_SERVICE));  
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);  
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);  
            // second element in paths[] is secondary storage path  
            return paths.length <= 1 ? null : paths[1];  
        } catch (Exception e) {  
//            Log.e(TAG, "getSecondaryStoragePath() failed", e);  
        }  
        return null;  
    } 
	
	/* 鍒ゆ柇鏂囦欢MimeType鐨刴ethod */
	public static boolean isSpecifiedFileType(File f, int iFileType) {
		String type = "";
		String fName = f.getName();
		/* 鍙栧緱鎵╁睍鍚� */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();
		
		System.out.println("isSpecifiedFileType---fName: " + fName);
		System.out.println("isSpecifiedFileType---end: " + end);
		System.out.println("isSpecifiedFileType---iFileType: " + iFileType);

		/* 渚濇墿灞曞悕鐨勭被鍨嬪喅瀹歁imeType */
		if(FILE_TYPE_APP == iFileType)
		{
			 if (end.equals("apk")) {
				 System.out.println("isSpecifiedFileType---Curr FileType apk");
				 return true;
			} 
		}
		else if(FILE_TYPE_32550_OS == iFileType)
		{
			 if (end.equals("bin")) {
				 System.out.println("isSpecifiedFileType---Curr FileType bin");
				 return true;
			} 
		}
		else if(FILE_TYPE_FIRMWARE == iFileType)
		{
			 if (end.equals("zip")) {
				 System.out.println("isSpecifiedFileType---Curr FileType zip");
				 return true;
			} 
		}
		
		System.out.println("isSpecifiedFileType---Curr FileType undefine");
		return false;
	}
	
    //鏂囦欢鎷疯礉
    //瑕佸鍒剁殑鐩綍涓嬬殑鎵�鏈夐潪瀛愮洰褰�(鏂囦欢澶�)鏂囦欢鎷疯礉
    public static int CopySdcardFile(String srcFile, String destFile)
    {
    	InputStream fosfrom = null;
    	OutputStream fosto = null;
    	
        try
        {   
        	fosfrom = new FileInputStream(srcFile);
        	fosto = new FileOutputStream(destFile);
            byte bt[] = new byte[1024];
            int c;
            
            while ((c = fosfrom.read(bt)) > 0)
            {
                fosto.write(bt, 0, c);
            }
            
            fosfrom.close();
            fosto.close();
            return 0;
             
        } 
        catch (Exception ex)
        {
        	ex.printStackTrace();
            try {
            	if(null != fosfrom)
            		fosfrom.close();
            	if(null != fosto)
            		fosto.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          
        }
        
        return -1;
    }
    
    public static int copy(String srcFile, String destFile, int iFileType)
    {
        //瑕佸鍒剁殑鏂囦欢鐩綍
        File[] currentFiles;
        File root = new File(srcFile);
        //濡傚悓鍒ゆ柇SD鍗℃槸鍚﹀瓨鍦ㄦ垨鑰呮枃浠舵槸鍚﹀瓨鍦�
        //濡傛灉涓嶅瓨鍦ㄥ垯 return鍑哄幓
        if(!root.exists())
        {
            return -1;
        }
        //濡傛灉瀛樺湪鍒欒幏鍙栧綋鍓嶇洰褰曚笅鐨勫叏閮ㄦ枃浠� 濉厖鏁扮粍
        currentFiles = root.listFiles();
         
        //鐩爣鐩綍
        File targetDir = new File(destFile);
        //鍒涘缓鐩綍
        if(!targetDir.exists())
        {
            targetDir.mkdirs();
        }
        //閬嶅巻瑕佸鍒惰鐩綍涓嬬殑鍏ㄩ儴鏂囦欢
        for(int i= 0;i<currentFiles.length;i++)
        {
            if(currentFiles[i].isDirectory())//濡傛灉褰撳墠椤逛负瀛愮洰褰� 杩涜閫掑綊
            {
              //  copy(currentFiles[i].getPath() + "/", destFile + currentFiles[i].getName() + "/", iFileType);
                 
            }
            else//濡傛灉褰撳墠椤逛负鏂囦欢鍒欒繘琛屾枃浠舵嫹璐�
            {
            	System.out.println("copy---currentFiles[i].name: " + currentFiles[i].getName());
            	System.out.println("copy---iFileType: " + iFileType);
            	if(isSpecifiedFileType(currentFiles[i], iFileType))
            	{
            		
            		int iRet =CopySdcardFile(currentFiles[i].getPath(), destFile + currentFiles[i].getName());
            		System.out.println("CopySdcardFile---iRet: " + iRet);	
            			System.out.println("copy---currentFiles[i].getPath: " + currentFiles[i].getPath());
            			System.out.println("copy---destFile + currentFiles[i].getName: " + destFile + currentFiles[i].getName());
            	}
            }
        }
        return 0;
    }
    
    public static List<File> getSpecifiedFileTypeList(String dir, int iFileType)
    {
        //瑕佸鍒剁殑鏂囦欢鐩綍
        File[] currentFiles;
        File root = new File(dir);
        //濡傚悓鍒ゆ柇SD鍗℃槸鍚﹀瓨鍦ㄦ垨鑰呮枃浠舵槸鍚﹀瓨鍦�
        //濡傛灉涓嶅瓨鍦ㄥ垯 return鍑哄幓
        if(!root.exists())
        {
            return null;
        }
        //濡傛灉瀛樺湪鍒欒幏鍙栧綋鍓嶇洰褰曚笅鐨勫叏閮ㄦ枃浠� 濉厖鏁扮粍
        currentFiles = root.listFiles();
        
        if(currentFiles.length <= 0)
        	return null;
        
        int fileNums = currentFiles.length;
        
        List<File> fileList = new ArrayList<File>();
        //閬嶅巻瑕佸鍒惰鐩綍涓嬬殑鍏ㄩ儴鏂囦欢
        for(int i= 0;i<fileNums;i++)
        {
            if(currentFiles[i].isDirectory())//濡傛灉褰撳墠椤逛负瀛愮洰褰� 杩涜閫掑綊
            {
    
            }
            else
            {
            	if(isSpecifiedFileType(currentFiles[i], iFileType))
            	{
            		fileList.add(currentFiles[i]);
            	}
            }
            
        }
        
        return fileList;
    }
    
	/**
	 * 鍒犻櫎鍗曚釜鏂囦欢
	 * 
	 * @param filePath
	 *            琚垹闄ゆ枃浠剁殑鏂囦欢鍚�
	 * @return 鏂囦欢鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse
	 */
	public static boolean deleteFile(String filePath) {
		File file = new File(filePath);
		final File tempFile = new File(file.getAbsolutePath() + System.currentTimeMillis());
		
		if (file.isFile() && file.exists()) {
			
			file.renameTo(tempFile);
			return tempFile.delete();
		}
		return false;
	}
    
	/**
	 * 鍒犻櫎鏂囦欢澶逛互鍙婄洰褰曚笅鐨勬枃浠�
	 * 
	 * @param filePath
	 *            琚垹闄ょ洰褰曠殑鏂囦欢璺緞
	 * @return 鐩綍鍒犻櫎鎴愬姛杩斿洖true锛屽惁鍒欒繑鍥瀎alse
	 */
	public static boolean deleteDirectory(String filePath) {
		boolean flag = false;
		// 濡傛灉filePath涓嶄互鏂囦欢鍒嗛殧绗︾粨灏撅紝鑷姩娣诲姞鏂囦欢鍒嗛殧绗�
		if (!filePath.endsWith(File.separator)) {
			filePath = filePath + File.separator;
		}
		File dirFile = new File(filePath);
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		flag = true;
		File[] files = dirFile.listFiles();
		
		if(null != files)
		{
			// 閬嶅巻鍒犻櫎鏂囦欢澶逛笅鐨勬墍鏈夋枃浠�(鍖呮嫭瀛愮洰褰�)
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					// 鍒犻櫎瀛愭枃浠�
					flag = deleteFile(files[i].getAbsolutePath());
					if (!flag)
						break;
				} else {
					// 鍒犻櫎瀛愮洰褰�
					flag = deleteDirectory(files[i].getAbsolutePath());
					if (!flag)
						break;
				}
			}
			if (!flag)
				return false;
			// 鍒犻櫎褰撳墠绌虹洰褰�
			return dirFile.delete();
		}
		
		return false;

	}
    
	/**
	 * 鏍规嵁璺緞鍒犻櫎鎸囧畾鐨勭洰褰曟垨鏂囦欢锛屾棤璁哄瓨鍦ㄤ笌鍚�
	 * 
	 * @param filePath
	 *            瑕佸垹闄ょ殑鐩綍鎴栨枃浠�
	 * @return 鍒犻櫎鎴愬姛杩斿洖 true锛屽惁鍒欒繑鍥� false銆�
	 */
	public static boolean DeleteFolder(String filePath) {
		File file = new File(filePath);
		if (!file.exists()) {
			return false;
		} else {
			if (file.isFile()) {
				// 涓烘枃浠舵椂璋冪敤鍒犻櫎鏂囦欢鏂规硶
				return deleteFile(filePath);
			} else {
				// 涓虹洰褰曟椂璋冪敤鍒犻櫎鐩綍鏂规硶
				return deleteDirectory(filePath);
			}
		}
	}
	
    public static int ReadFile(String fileName, byte[] byFileBuff) throws IOException{

    	int fileAbleLen = -1;
    	int fileLen = -1;
    	
        try{
        	
            FileInputStream fin = new FileInputStream(fileName);
            fileAbleLen = fin.available();
 
           
            fileLen = fin.read(byFileBuff);
            if(fileLen != fileAbleLen){
                fin.close();
                return -1;
            }

            Log.i("readFile", "fileLen: " + fileLen);
            fin.close();
        }
        catch(Exception e){
            e.printStackTrace();
            return -2;
        }

        return fileLen;
    }
    
    public static int CreateFolder(String strFileDir){

    	if(null == strFileDir)
    		return -1;
    	
    	try{
            //鐩爣鐩綍
            File targetDir = new File(strFileDir);
            //鍒涘缓鐩綍
            if(!targetDir.exists())
            {
                targetDir.mkdirs();
            }
            
            return 0;
    	}
    	catch(Exception e)
    	{
            e.printStackTrace();
            return -2;
    	}


    }
    
    ///////////////////////澶嶅埗鏂囦欢//////////////////////////////
    /** 
     * 澶嶅埗鍗曚釜鏂囦欢 
     * @param oldPath String 鍘熸枃浠惰矾寰� 濡傦細c:/fqf.txt 
     * @param newPath String 澶嶅埗鍚庤矾寰� 濡傦細f:/fqf.txt 
     * @return boolean 
     */
   public boolean copyFile(String oldPath, String newPath) { 
       boolean isok = true;
       try { 
           int bytesum = 0; 
           int byteread = 0; 
           File oldfile = new File(oldPath); 
           if (oldfile.exists()) { //鏂囦欢瀛樺湪鏃� 
               InputStream inStream = new FileInputStream(oldPath); //璇诲叆鍘熸枃浠� 
               FileOutputStream fs = new FileOutputStream(newPath); 
               byte[] buffer = new byte[1024]; 
               int length; 
               while ( (byteread = inStream.read(buffer)) != -1) { 
                   bytesum += byteread; //瀛楄妭鏁� 鏂囦欢澶у皬 
                   //System.out.println(bytesum); 
                   fs.write(buffer, 0, byteread); 
               } 
               fs.flush(); 
               fs.close(); 
               inStream.close(); 
           }
           else
           {
            isok = false;
           }
       } 
       catch (Exception e) { 
          // System.out.println("澶嶅埗鍗曚釜鏂囦欢鎿嶄綔鍑洪敊"); 
          // e.printStackTrace(); 
           isok = false;
       } 
       return isok;
 
   } 
 
   /** 
     * 澶嶅埗鏁翠釜鏂囦欢澶瑰唴瀹� 
     * @param oldPath String 鍘熸枃浠惰矾寰� 濡傦細c:/fqf 
     * @param newPath String 澶嶅埗鍚庤矾寰� 濡傦細f:/fqf/ff 
     * @return boolean 
     */
   public static boolean copyFolder(String oldPath, String newPath) { 
       boolean isok = true;
       try { 
           (new File(newPath)).mkdirs(); //濡傛灉鏂囦欢澶逛笉瀛樺湪 鍒欏缓绔嬫柊鏂囦欢澶� 
           File a=new File(oldPath); 
           String[] file=a.list(); 
           File temp=null; 
           for (int i = 0; i < file.length; i++) { 
               if(oldPath.endsWith(File.separator)){ 
                   temp=new File(oldPath+file[i]); 
               } 
               else
               { 
                   temp=new File(oldPath+File.separator+file[i]); 
               } 
 
               if(temp.isFile()){ 
                   FileInputStream input = new FileInputStream(temp); 
                   FileOutputStream output = new FileOutputStream(newPath + "/" + 
                           (temp.getName()).toString()); 
                   byte[] b = new byte[1024 * 5]; 
                   int len; 
                   while ( (len = input.read(b)) != -1) { 
                       output.write(b, 0, len); 
                   } 
                   output.flush(); 
                   output.close(); 
                   input.close(); 
               } 
               if(temp.isDirectory()){//濡傛灉鏄瓙鏂囦欢澶� 
                   copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
               } 
           } 
       } 
       catch (Exception e) { 
            isok = false;
       } 
       return isok;
   }

}
